package com.netty.demo.nio.handler;

import com.netty.demo.protocol.packet.*;
import com.netty.demo.utils.ConsoleUtils;
import com.netty.demo.utils.LoginUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.Scanner;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        ByteBuf requestByteBuf = (ByteBuf) msg;

        Packet packet = PacketCodec.INSTANCE.decoder(requestByteBuf);
        if (packet instanceof LoginRequestPacket) {
            // 登录流程
            LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
            System.out.println(new Date() + ": 客户端（" + loginRequestPacket.getUserId() + "）开始登录……");

            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());
            if (LoginUtils.valid(loginRequestPacket)) {
                loginResponsePacket.setSuccess(true);
                loginResponsePacket.setUserId(loginRequestPacket.getUserId());
                System.out.println(new Date() + ": 登录成功!");
            } else {
                loginResponsePacket.setReason("账号密码校验失败");
                loginResponsePacket.setSuccess(false);
                System.out.println(new Date() + ": 登录失败!");
            }
            // 登录响应
            ByteBuf responseByteBuf = PacketCodec.INSTANCE.encoder(ctx.alloc().buffer(), loginResponsePacket);
            ctx.channel().writeAndFlush(responseByteBuf);
            LoginUtils.recordLogin(ctx.channel(), loginRequestPacket.getUserId());
        } else if (packet instanceof MessagePacket) {
            MessagePacket messagePacket = (MessagePacket) packet;
            System.out.println("收到用户（" + messagePacket.getUserId() + "）于（" + messagePacket.getSendTime() + "）发送的消息：" + messagePacket.getMessage());
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception{
        super.channelActive(ctx);
        ConsoleUtils.startServerConsoleThread();
    }
}
